/**
 * Copyright (C), 2020-2021 by colley.ma
 * File Name: DistributedLockAutoConfiguration.java
 * Encoding: UTF-8
 * Date: 2021年12月28日 下午3:36:20
 * History:
 */
package com.swak.frame.lock.spring.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.swak.frame.SwakConstants;
import com.swak.frame.cache.CacheProxy;
import com.swak.frame.lock.DistributedLock;
import com.swak.frame.lock.RenewalDistributedLock;
import com.swak.frame.system.SwakAbstractConfiguration;
import com.swak.frame.timer.WheelTimerHolder;
import com.swak.frame.ump.adapter.AlarmEventAdapter;

@Configuration
@ConditionalOnProperty(prefix = SwakConstants.SWAK_CACHE, name = "enabled", havingValue = "true",
    matchIfMissing = false)
public class DistributedLockAutoConfiguration extends SwakAbstractConfiguration {

    private final static String RENEWAL_ENABLED = SwakConstants.SWAK_LOCK + ".enabled";

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(CacheProxy.class)
    public DistributedLock distributedLock(CacheProxy cacheProxy, AlarmEventAdapter alarmEventAdapter) {
        RenewalDistributedLock distributedLock = new RenewalDistributedLock();
        distributedLock.setCacheProxy(cacheProxy);
        distributedLock.setAlarmEventAdapter(alarmEventAdapter);
        distributedLock.setWheelTimer(WheelTimerHolder.lockWatchWheel());
        // 是否开启续租
        distributedLock.setRenewalEnabled(systemConfig.getBoolean(RENEWAL_ENABLED, true));
        return distributedLock;
    }
}
